package org.cupk2.service.event;

import com.cupk2.lucene.document.CupkDocument;
import com.cupk2.lucene.impl.Cupk2LuceneIndexImpl;
import com.cupk2.lucene.inter.Cupk2LuceneIndexInter;
import com.cupk2.lucene.utils.CupkLuceneUtils;
import lombok.extern.slf4j.Slf4j;
import org.cupk2.base.event.F2Event;
import org.cupk2.base.event.enums.F2EActionT;
import org.cupk2.base.event.inter.Cupk2EventHandle;
import org.cupk2.files.service.ResourceFileServiceInter;
import org.cupk2.files.utils.Cupk2RegisteTypeEnum;
import org.cupk2.files.utils.FileDownloadUtils;
import org.cupk2.llm.service.LlmClientServiceInter;
import org.cupk2.service.event.utils.KnowIndexDocumentBuilder;
import org.cupk2.service.inter.CupkUserServiceInter;
import org.cupk2.service.lucene.doc.enums.DocumentTitleEnum;
import org.cupk2.zhzm.domain.ZhzmKnow;
import org.cupk2.zhzm.service.ZhzmKnowServiceInter;
import org.cupk2.wdap.service.WdapExtendFileServiceInter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 创建附件索引
 */
@Slf4j
@Service
public class EventLuceneEmbeddingHandle implements Cupk2EventHandle {
    @Autowired
    private ResourceFileServiceInter resourceFileServiceImpl;
    @Autowired
    private FileDownloadUtils fileDownloadUtils;
    @Autowired
    private WdapExtendFileServiceInter wdapExtendFileServiceImpl;
    @Autowired
    private CupkUserServiceInter cupkUserService;
    @Autowired
    private ZhzmKnowServiceInter zhzmKnowServiceImpl;
    @Autowired
    private LlmClientServiceInter llmClientServiceImpl;
    @Autowired
    private KnowIndexDocumentBuilder knowIndexDocumentBuilder;
    @Override
    public void handle(F2Event event) {

        if (event.getAction().getType().equals(F2EActionT.EXTEND_FILE)) {
            String fileId = event.getObj().getId();
            String knowId = resourceFileServiceImpl.getBindAppId(fileId, Cupk2RegisteTypeEnum.KNOW);
            Cupk2LuceneIndexInter indexService = new Cupk2LuceneIndexImpl(CupkLuceneUtils.getLuceneEmbeddingFilePath());
            ZhzmKnow know = zhzmKnowServiceImpl.getZhzmKnowById(knowId);
            List<CupkDocument> documents = null;
            documents = knowIndexDocumentBuilder.getVectorDoc(knowId, fileId);
            indexService.deleteIndex(List.of(fileId), DocumentTitleEnum.fileId.name());
            indexService.createIndex(documents);
        }

        if (event.getAction().getType().equals(F2EActionT.CANCEL_FILE)) {
            String fileId = event.getObj().getId();

            Cupk2LuceneIndexInter indexService = new Cupk2LuceneIndexImpl(CupkLuceneUtils.getLuceneEmbeddingFilePath());
            indexService.deleteIndex(List.of(fileId),DocumentTitleEnum.fileId.name());
        }
    }


}
